package com.rong.deepseek.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.rong.deepseek.config.AiConfig;
import com.rong.deepseek.service.AiService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author 周厚荣
 * @date 2025/3/31 20:40
 */
@Slf4j
@Service("aiService")
public class AiServiceImpl implements AiService {
    @Resource
    private AiConfig aiConfig;
    @Override
    public String sendText(String context) {
        if (aiConfig.getApiKey() == null || aiConfig.getApiKey().isEmpty()) {
            return "API密钥未设置，请配置环境变量 DEEPSEEK_API_KEY";
        }
        String response = "";
        try {
            response = sendDeepseekChat(aiConfig.getBaseUrl(), context);
            System.out.println("API响应结果：");
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 发送 Deepseek 对话请求
     *
     * @param deepseekUrl API地址
     * @param context     对话内容
     * @return 返回结果字符串
     * @throws IOException
     */
    public String sendDeepseekChat(String deepseekUrl, String context) throws IOException {
        String result = null;
        String message_result = "";
        URL url = new URL(deepseekUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // 增强 SSL 校验，防止中间人攻击
        SSLSocketFactory oldSocketFactory = trustAllHosts(connection);

        try {
            // 设置请求参数
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(60000);
            connection.setReadTimeout(60000);
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Authorization", "Bearer " + aiConfig.getApiKey());

            // 构建请求数据
            JSONObject requestData = new JSONObject();
            JSONArray messages = new JSONArray();

            // 系统消息
            JSONObject systemMessage = new JSONObject();
            systemMessage.put("content", aiConfig.getMessages().get(0).getContent());
            systemMessage.put("role", aiConfig.getMessages().get(0).getRole());
            // 用户消息
            JSONObject userMessage = new JSONObject();
            userMessage.put("content", context);
            userMessage.put("role", aiConfig.getMessages().get(1).getRole());

            messages.add(systemMessage);
            messages.add(userMessage);

            requestData.put("messages", messages);
            requestData.put("model", "deepseek-chat");
            requestData.put("max_tokens", aiConfig.getMax_tokens());
            requestData.put("temperature", aiConfig.getTemperature());

            // 发送数据
            try (OutputStream os = connection.getOutputStream()) {
                os.write(requestData.toJSONString().getBytes("UTF-8"));
            }

            // 读取响应数据
            try (InputStream in = connection.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {

                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }

                result = response.toString();

                // 使用 Fastjson2 解析 JSON 响应
                JSONObject jsonResponse = JSON.parseObject(result);
                JSONArray choices = jsonResponse.getJSONArray("choices");
                if (choices != null && !choices.isEmpty()) {
                    JSONObject message = choices.getJSONObject(0).getJSONObject("message");
                    message_result =message.getString("content");
                }
            }

        } finally {
            // 恢复 SSL 套接字工厂
            connection.setSSLSocketFactory(oldSocketFactory);
        }

        return message_result;
    }

    /**
     * 信任所有证书（仅用于测试环境）
     */
    private SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
        SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            SSLSocketFactory newFactory = sc.getSocketFactory();
            connection.setSSLSocketFactory(newFactory);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return oldFactory;
    }

    /**
     * 信任所有证书（仅用于测试环境）
     */
    private final TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{};
                }

                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
            }
    };
}
